
package com.gitee.jmash.rbac.dao;

import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.orm.jpa.BaseDao;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.rbac.entity.UsersRolesEntity;
import com.gitee.jmash.rbac.entity.UsersRolesEntity.UsersRolesPk;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * UsersRoles实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class UsersRolesDao extends BaseDao<UsersRolesEntity, UsersRolesPk> {

  public UsersRolesDao() {
    super();
  }

  public UsersRolesDao(TenantEntityManager tem) {
    super(tem);
  }

  /**
   * 获取用户角色.
   */
  public List<UUID> findUserRoles(UUID userId) {
    String sql = "select s.roleId from UsersRolesEntity s where  s.userId = ?1 ";
    return this.findList(sql, UUID.class, userId);
  }

  /**
   * 移除用户角色.
   */
  public int removeByUserId(UUID userId) {
    // 避免死锁 https://blog.csdn.net/weixin_39183543/article/details/134777281
    List<UsersRolesEntity> list =
        this.findList("from UsersRolesEntity s where s.userId = ?1 ", userId);
    return this.removeAll(list);
  }


  /** 移除用户角色. */
  public int removeByRoleId(UUID roleId) {
    // 避免死锁 https://blog.csdn.net/weixin_39183543/article/details/134777281
    List<UsersRolesEntity> list =
        this.findList("from UsersRolesEntity s where s.roleId = ?1 ", roleId);
    return this.removeAll(list);
  }

  /** 新增用户角色. */
  public void addUserRoles(UUID userId, List<String> roleIds) {
    if (roleIds == null || roleIds.isEmpty()) {
      return;
    }
    Set<String> roleIdSet = roleIds.stream().collect(Collectors.toSet());
    for (String roleId : roleIdSet) {
      UsersRolesEntity entity = new UsersRolesEntity(userId, UUIDUtil.fromString(roleId));
      this.persist(entity);
    }
  }

  /** 更新用户角色. */
  public void updateUserRoles(UUID userId, List<String> roleIds) {
    this.removeByUserId(userId);
    this.addUserRoles(userId, roleIds);
  }

  /** 查询关联角色数量. */
  public int isRelationRole(UUID roleId) {
    String sql = "select count(s.userId) from UsersRolesEntity s where s.roleId = ?1 ";
    return Integer.parseInt(this.findSingleResult(sql, roleId).toString());
  }

}
